package com.study.gank.ui.fragment

import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.study.gank.bean.GankGoods
import com.study.gank.databinding.ViewRecyclerBinding
import com.study.gank.di.component.GankGoodsModule
import com.study.gank.getMainComponent
import com.study.gank.mvp.contract.GankGoodsContract
import com.study.gank.mvp.presenter.GankGoodsPresenter
import com.study.gank.router.GankClientUri
import com.study.gank.router.GankRouter
import com.study.gank.ui.adapter.GankGoodsAdapter
import java.net.URLDecoder
import javax.inject.Inject

class IOSFragment : BaseBindingFragment<ViewRecyclerBinding>(), GankGoodsContract.View {

    private var mPage = 1
    lateinit var mAdapter: GankGoodsAdapter
    private var mDatas = mutableListOf<GankGoods>()

    @Inject
    lateinit var mPresenter: GankGoodsPresenter

    override fun createDataBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): ViewRecyclerBinding {
        return ViewRecyclerBinding.inflate(inflater, container, false)
    }

    override fun initView() {
        mAdapter = GankGoodsAdapter(mDatas)
        mContext.getMainComponent().buildGankGoodsComponent(GankGoodsModule(this)).inject(this)
        with(mBinding) {
            recyclerView.adapter = mAdapter
            recyclerView.layoutManager = LinearLayoutManager(mContext)
            recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    if (!recyclerView.canScrollVertically(1)) {
                        // 不能继续向上滚动
                        mPresenter.getdata(++mPage, IOS)
                    }
                }
            })
        }
        mAdapter.setOnItemClickListener {
            val url = Uri.encode(mDatas[it].url)
            GankRouter.router(mContext,  URLDecoder.decode(url, "utf-8"))
        }
        mPresenter.getdata(mPage, IOS)
    }


    override fun onShowData(datas: List<GankGoods>) {
        mDatas.addAll(datas)
        mAdapter.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.unSubscribe()
    }

    companion object {
        const val IOS = "IOS"

        fun newInstance(): IOSFragment {
            val fragment = IOSFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }
    }
}